 package edu.vt.ece3574.ninjatag;

/****************************************************************************
 * Copyright 2012 Landon Biggs, Chris Dusold, Brad Russell, and Craig Wertz	*
 * Licensed under the Apache License, Version 2.0 (the "License");			*
 * you may not use this file except in compliance with the License.			*
 * You may obtain a copy of the License at									*
 * 																			*
 * http://www.apache.org/licenses/LICENSE-2.0								*
 * 																			*
 * Unless required by applicable law or agreed to in writing, software		*
 * distributed under the License is distributed on an "AS IS" BASIS,		*
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.	*
 * See the License for the specific language governing permissions and		*
 * limitations under the License.											*
 ****************************************************************************/

import java.io.IOException;
import java.net.MalformedURLException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.facebook.android.Utility;

public class NinjaTagActivity extends Activity implements OnClickListener{

	private Facebook facebook = new Facebook("208547072576022");
	private int fbStatus = 0; // This is a temp solution. There should be a more elegant solution. -Chris
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* TODO This is for debugging. It will let a programmer jump to the activity they want to test.
		//*/// <- Insert space to the right of the * to comment out normal code. NOTE: NOT DEAD CODE!
        
        // This locks the orientation, you can unlock it later with:
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        this.setRequestedOrientation(
        		ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.main);
	    ConnectivityManager cm =
		        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo == null || !netInfo.isConnected()) {
			Intent noConnectionIntent = new Intent(NinjaTagActivity.this, no_internet_screen.class);
			startActivity(noConnectionIntent);
			finish();
	    }
        SessionStore.restore(facebook, getApplicationContext());
    	if (facebook.isSessionValid()) {
        	setContentView(R.layout.loggingin);
        	final TextView logintext = (TextView) findViewById(R.id.logintext);
        	final Button buttonAux = (Button) findViewById(R.id.buttonLoginAux);
        	buttonAux.setOnClickListener(this);
        	logintext.setText("Welcome back!");
        	fbStatus=3;
        	buttonAux.setText("Continue");
        	
    	}  /*/ //  <- This will switch for use the of debugging code. NOTE: NOT DEAD CODE!
        SessionStore.restore(facebook, getApplicationContext()); //Will not work if stored access token is bad.
        Utility.setup(facebook);
        Intent intent = new Intent(NinjaTagActivity.this, matchmaking_screen.class); //change .class to the one being tested.
        startActivity(intent);
        finish();
        //*/
    	
    	
    	
    	
    }
    
	/*
	 *	The next couple methods are used to override the menu and back physical buttons on the phone.
	 *	onCreateOptionsMenu sets the menu to the custom 'main_menu'
	 *	onOptionsItemSelected starts an activity based on the selected option in the menu
	 * 	onBackPressed sends the app to the previous screen.
	 * 		-disabled on this activity
	 */
	
    @Override
	public void onBackPressed(){
		
		return;
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_menu, menu);
    	return true;
    }
    
    // End Override Methods
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch(item.getItemId() ){
    	
    	case R.id.menu_home:
    		Intent mainScreenIntent = new Intent(NinjaTagActivity.this, main_screen.class);
    		startActivity(mainScreenIntent);
    		finish();
    		break;
    		
    	
    	case R.id.menu_map:
    		Intent mapScreenIntent = new Intent(NinjaTagActivity.this, map_screen.class);
    		startActivity(mapScreenIntent);
    		finish();
    		break;
    		
    	case R.id.menu_settings:
    		Intent settingsScreenIntent = new Intent(NinjaTagActivity.this, settings_screen.class);
    		startActivity(settingsScreenIntent);
    		finish();
    		break;
    		
    	case R.id.gps_settings:
    		Intent GPS_ActivityIntent = new Intent(NinjaTagActivity.this, GPS_Activity.class);
    		startActivity(GPS_ActivityIntent);
    		finish();
    		break;
    		
    	case R.id.menu_lock_or:
			
			if(getOrientation() == Configuration.ORIENTATION_PORTRAIT){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				break;
			}
		
			else if(getOrientation() == Configuration.ORIENTATION_LANDSCAPE){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				break;
			}
			else Toast.makeText(getBaseContext(), "Error: orientation was not locked", Toast.LENGTH_SHORT).show();
			break;
			
    	case R.id.menu_unlock_or:
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			break;
    	}
    	return true;
    }
    
    //This activates Facebook's Activity result callbacks.
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
    
    //when login button is pressed
    //*
    public void loginClick(View view){
    	fbStatus = 1;
    	setContentView(R.layout.loggingin);
    	final TextView logintext = (TextView) findViewById(R.id.logintext);
    	final Button buttonAux = (Button) findViewById(R.id.buttonLoginAux);
    	buttonAux.setOnClickListener(this);
		facebook.authorize(NinjaTagActivity.this, new DialogListener() {

			@Override
			public void onFacebookError(FacebookError er) {
		        Log.e("Facebook", er.getMessage());
		        er.printStackTrace();
            	logintext.setText("There was a Facebook error.");
            	try {
					facebook.logout(NinjaTagActivity.this);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
            	fbStatus=2;
            	buttonAux.setText("Retry");
				
			}
			
			@Override
			public void onError(DialogError er) {
		        Log.e("Facebook", er.getMessage());
		        er.printStackTrace();
            	logintext.setText("There was an error.");
            	try {
					facebook.logout(NinjaTagActivity.this);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
            	fbStatus=2;
            	buttonAux.setText("Retry");
				
			}
			
			@Override
			public void onComplete(Bundle arg0) {
	            SessionStore.save(facebook,getApplicationContext());
            	logintext.setText("You have successfully logged in.");
            	fbStatus=3;
            	buttonAux.setText("Continue");
				
			}
			
			@Override
			public void onCancel() {
            	logintext.setText("The logging in routine was canceled.");
            	fbStatus=2;
            	buttonAux.setText("Retry");
				
			}
		});
    }
    

	private void auxClick(View v) {
		Intent startIntent = new Intent(NinjaTagActivity.this, main_screen.class);
		
		switch(fbStatus) {
		case 0:
			System.err.println("Umm... I think you broke it.");
			break;
		case 1:
			System.err.println("It doesn't appear you can cancel it this way. Sorry.");
			break;
		case 2:
			loginClick(v);
			break;
		case 3:
	        Utility.setup(facebook);
			startActivity(startIntent);
			finish();
			break;
		default:
			System.err.println("Wait... How did you do that?");
			break;
		}
		
	}

	@Override
	public void onClick(View v) {
		
		switch(v.getId()) {
		
		case R.id.buttonLogin:
			loginClick(v);
			break;
			
		case R.id.buttonLoginAux:
			auxClick(v);
			break;
		}
	}
	public int getOrientation()
	{
	    Display getOrient = getWindowManager().getDefaultDisplay();
	    int orientation = Configuration.ORIENTATION_UNDEFINED;
	    if(getOrient.getWidth()==getOrient.getHeight()){
	        orientation = Configuration.ORIENTATION_SQUARE;
	    } else{ 
	        if(getOrient.getWidth() < getOrient.getHeight()){
	            orientation = Configuration.ORIENTATION_PORTRAIT;
	        }else { 
	             orientation = Configuration.ORIENTATION_LANDSCAPE;
	        }
	    }
	    return orientation;
	}

}

